package com.zzx.test.thread.juc;

import java.util.concurrent.RecursiveTask;

/**
 * @ClassName: ForkJoinDemo
 * @Description: ForkJoin测试实体类
 * @Author zhouzhixin
 * @Date 2021/11/9
 * @Version 1.0
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private long start;
    private long end;

    public ForkJoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        if (end - start < 100_0000L) {
            long sum = 0L;
            for (long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2L;
            ForkJoinDemo forkJoinDemo1 = new ForkJoinDemo(start, middle);
            ForkJoinDemo forkJoinDemo2 = new ForkJoinDemo(middle + 1, end);
            forkJoinDemo1.fork();
            forkJoinDemo2.fork();
            return forkJoinDemo1.join() + forkJoinDemo2.join();
        }
    }

}
